package com.fzu.geometa.metadata.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    public static int getHierarchyCount(String jsonString) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonString);
        return countHierarchy(rootNode);
    }

    private static int countHierarchy(JsonNode node) {
        int maxHierarchyCount = 0;
        if (node.isObject()) {
            for (JsonNode childNode : node) {
                int hierarchyCount = countHierarchy(childNode);
                if (hierarchyCount > maxHierarchyCount) {
                    maxHierarchyCount = hierarchyCount;
                }
            }
            return maxHierarchyCount + 1;
        } else if (node.isArray()) {
            for (JsonNode childNode : node) {
                int hierarchyCount = countHierarchy(childNode);
                if (hierarchyCount > maxHierarchyCount) {
                    maxHierarchyCount = hierarchyCount;
                }
            }
            return maxHierarchyCount + 1;
        } else {
            return 1;
        }
    }
}
